<?php

namespace app\model;

use think\Model;
use think\model\relation\HasOne;

class Account extends Model
{
    public function store(): HasOne
    {
        return $this->hasOne(Store::class, 'id', 'store_id');
    }

    public function supplier(): HasOne
    {
        return $this->hasOne(Supplier::class, 'id', 'supplier_id');
    }

    public function getPage(): array
    {
        $param = request()->get();
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 50;
        $data = $this->with(['store', 'supplier'])->when(!empty($param['name']), function ($query) use ($param) {
            $query->whereLike('name', '%' . $param['name'] . '%');
        })->when(!empty($param['mobile']), function ($query) use ($param) {
            $query->whereLike('mobile', '%' . $param['mobile'] . '%');
        })->when(!empty($param['store_id']), function ($query) use ($param) {
            $query->where('store_id', $param['store_id']);
        })->when(!empty($param['supplier_id']), function ($query) use ($param) {
            $query->where('supplier_id', $param['supplier_id']);
        })->when(!empty($param['state']), function ($query) use ($param) {
            $query->where('state', $param['state']);
        })->when(!empty($param['type']), function ($query) use ($param) {
            $query->where('type', $param['type']);
        })->where(['is_del' => 1])->order(['create_time' => 'desc'])->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total']];
    }

    public function updateOrAdd(): array
    {
        $param = request()->post();
        unset($param['create_time'], $param['update_time']);
        //判断手机号是否已注册
        $count = $this->where(['mobile' => $param['mobile'], 'is_del' => 1])->when(!empty($param['id']), function ($query) use ($param) {
            $query->where('id', '<>', $param['id']);
        })->count();
        if ($count > 0) throw new \Exception("该手机号已注册", 700123);
        $acc = $param['mobile'];
        if ($count > 0) {
            //将字符按长度分割成数组
            $arr = str_split($param['mobile'], 1);
            $acc .= bcadd(bcadd(bcadd($param['supplier_id'], 1000), array_sum($arr)), rand(100, 999));
        }
        if ($param['type'] == 2 && empty($param['id'])) {
            //获取当前门店充值的金额
            $storeBalance = Store::where(['id' => $param['store_id']])->value('balance');
            $param['balance'] = $storeBalance;
        }
        if (empty($param['id'])) {
            $param['account'] = $acc;
            $password = setPassword("123456");
            $param['password'] = $password['password'];
            $param['decode'] = $password['encode'];
        } else unset($param['password'], $param['decode']);
        $this->exists(!empty($param['id']))->save($param);
        return $this->toArray();
    }

    public function deleteAccount()
    {
        $id = request()->param("id");
        $balance = $this->where(['id' => $id])->value('balance');
        if ($balance > 0) throw new \Exception("该账户余额不为0，无法删除", 700123);
        $this->where(['id' => $id])->update(['is_del' => 0]);
        return $this->find($id);
    }

    public function changeState(): array
    {
        $param = request()->post();
        $this->where(['id' => $param['id']])->update(['state' => $param['state']]);
        return $this->toArray();
    }

    public function phoneDetail()
    {
        $phone = request()->param("mobile");

        $data = $this->where(['mobile' => $phone, 'is_del' => 1, 'state' => 1])->find();
        if (empty($data)) {
            throw new \Exception("该手机号未注册", 7025);
        }
        return $data;
    }

    public function accountDetail()
    {
        $account = request()->param("mobile");
        $data = $this->where(['account' => $account, 'is_del' => 1, 'state' => 1])->find();
        if (empty($data)) {
            throw new \Exception("该账号不存在", 7025);
        }
        return $data;
    }

    public function getDetail($id)
    {
        return $this->with(['store', 'supplier' => function ($query) {
            $query->with(['appid']);
        }])->findOrFail($id);
    }

    public function searchAccountLst(): array
    {
        $store_id = request()->param('store');
        return $this->where(['store_id' => $store_id, 'type' => 3, 'is_del' => 1])->column("id,name");
    }

    public function addBalance()
    {
        $param = request()->post();
        $this->startTrans();
        $store_id = $this->where(['id' => $param['aid']])->value("store_id");
        $stores = app(Store::class);
        if ($param['state'] == 1) {
            //获取店长账户余额
            $balance = $this->where(['id' => $param['sid'], 'is_del' => 1])->value('balance');
            $allBalance = $stores->where(['id' => $store_id, 'is_del' => 1])->value('balance');
            if ($param['number'] > bcdiv($balance, 100, 2) || $param['number'] > bcdiv($allBalance, 100, 2)) throw new \Exception("授权金额不能大于店长账户余额", 7025);
            $this->where(['id' => $param['aid']])->inc("balance", bcmul($param['number'], 100))->save();
//            dd($store_id);
            $this->where(['store_id' => $store_id, 'type' => 2, 'is_del' => 1])->dec("balance", bcmul($param['number'], 100))->save();
            $stores->where(['id' => $store_id, 'is_del' => 1])->dec('balance', bcmul($param['number'], 100))->save();
        } else {
            $balance = $this->where(['id' => $param['aid'], 'is_del' => 1])->value('balance');
            if ($param['number'] > bcdiv($balance, 100, 2)) throw new \Exception("回收金额不能大于账户余额", 7025);
            $this->where(['id' => $param['aid']])->dec("balance", bcmul($param['number'], 100))->save();
            $this->where(['store_id' => $store_id, 'type' => 2, 'is_del' => 1])->inc("balance", bcmul($param['number'], 100))->save();
            $stores->where(['id' => $store_id, 'is_del' => 1])->inc('balance', bcmul($param['number'], 100))->save();
        }
        $param['number'] = bcmul($param['number'], 100);
        app(AccountApply::class)->save($param);
        $this->commit();
        return $this->find($param['aid']);
    }
}
